#!/bin/bash

apt-get update

sudo apt-get install -y apache2
sudo apt install -y php libapache2-mod-php php-mysql php-common php-gd php-xml php-mbstring php-zip php-curl

SIP=$(hostname -I | awk '{print $1}')
cat > /etc/apache2/sites-available/nextcloud.conf << EOF
<VirtualHost *:80>
    ServerAdmin admin@example.com
    DocumentRoot /var/www/html/nextcloud/
    ServerName $SIP

    <Directory /var/www/html/nextcloud/>
        Options +FollowSymlinks
        AllowOverride All
        Require all granted
        <IfModule mod_dav.c>
            Dav off
        </IfModule>
        SetEnv HOME /var/www/html/nextcloud
        SetEnv HTTP_HOME /var/www/html/nextcloud
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/error.log
    CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF
sync

sudo ln -s /etc/apache2/sites-available/nextcloud.conf /etc/apache2/sites-enabled/
sudo a2enmod headers rewrite env dir mime
sudo systemctl restart apache2 --no-page -l

sudo apt-get install -y mariadb-server

mysql_secure_installation << EOF
n
n
n
n
n
n
n
EOF

DATEBASE_NAME="nextcloud"
USER_DATATABLE_NAME="nextclouduser"
read -p "创建数据库（$DATEBASE_NAME）和用户表（$USER_DATATABLE_NAME），请设置数据表密码: " DB_PASSWD

mysql -u root -p "" << EOF
CREATE DATABASE $DATEBASE_NAME;
GRANT ALL ON $DATEBASE_NAME.* TO '$USER_DATATABLE_NAME'@'localhost' IDENTIFIED BY '$DB_PASSWD';
EOF

echo "创建数据库（$DATEBASE_NAME）和用户表（$USER_DATATABLE_NAME）完成，密码为：$DB_PASSWD"

tar xvf nextcloud-25.0.13.tar.bz2
sudo mv nextcloud /var/www/html/
sudo mkdir -p /var/www/html/nextcloud/data
sudo chown -R www-data:www-data /var/www/html/nextcloud/
sudo chmod -R 755 /var/www/html/nextcloud/

read -p "安装完成，请在浏览器中输入http://$SIP/nextcloud 执行后续操作。按任意键退出。 "
